﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using System.Windows.Forms;
using System.Threading;

using ClassLibraryOverLog;
namespace LogRecord
{
    
    public class Log
    {
        private string mPathName = Application.StartupPath + "\\" + "log";
        private int mSum = 0;
        public readonly static Log mInstance = new Log();
        /// <summary>
        /// 设置日志存放路径
        /// </summary>
        public string PathName
        {
            set
            {
                mPathName = Application.StartupPath + "\\" + value; 
            }
        }

        private Log()
        {
            if(Directory.Exists(mPathName))
            {

            }else
            {
                Directory.CreateDirectory(mPathName);
            }
            Thread myThread = new Thread(new ParameterizedThreadStart(printflog));
            myThread.Priority = ThreadPriority.Normal;
            myThread.IsBackground = true;
            myThread.Start(this); 
        }
        private object _plock = new object();

        public FormLogShow showlogForm = null;
        public bool showlogFormCanUsed = false;
        public  TextBox textboxlog = null;
        public void  JustLogShowInForm()
        {
            if(showlogForm!=null)
            {
                MessageBox.Show("已经打开");
                return;
            }
            showlogForm = new FormLogShow();
            showlogForm.refrenseLogClass = this;
            showlogFormCanUsed = true;
            textboxlog = showlogForm.ReturnTextbox();
            showlogForm.Show();

        }


        private void printflog(object p)
        {
            while (true)
            {
                StringBuilder strData = null;
             
                bool iscount = false;
                lock (_plock)
                {
              
                if (printstring.Count > 0)
                {
                    iscount = true;
                    strData = printstring[0].strb;
      
                    printstring.RemoveAt(0);
                }
                else
                {
                    iscount = false;
                }

               }
                if (iscount)
                {            
                    StringBuilder strFile = new StringBuilder();
                    strFile.AppendFormat("{0}\\{1}\\{2}\\", mPathName, DateTime.Now.Year.ToString(), DateTime.Now.Month.ToString());
                    if (!Directory.Exists(strFile.ToString()))
                    {
                        Directory.CreateDirectory(strFile.ToString());
                    }
                    //将数据写入文件中
                    strFile.Append(DateTime.Now.ToString("yyyy-MM-dd") + ".txt");
                    using (StreamWriter swAppend = File.AppendText(strFile.ToString()))
                    {
                        swAppend.WriteLine(Convert.ToString(strData));
                        swAppend.Flush();
                        swAppend.Close();
                    }                
                    if (showlogFormCanUsed && textboxlog != null)
                    {
                        textboxlog.Invoke((EventHandler)(delegate
                        {

                       if( textboxlog.Text.Length>1999999)
                        {
                            textboxlog.Clear();

                        }                  
                        textboxlog.AppendText(Convert.ToString(strData) + "\r\n");
                        }));
                    }else
                    {

                    }

                }else
                {
                    Thread.Sleep(2);
                }
            }
        }
        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="strFile"></param>
        /// <param name="strData"></param>
        public void WriteLog(string strData, ref bool create)
        {
            //创建文件夹
            StringBuilder strFile = new StringBuilder();
            strFile.AppendFormat("{0}\\{1}\\{2}\\", mPathName, DateTime.Now.Year.ToString(), DateTime.Now.Month.ToString());
            if (!Directory.Exists(strFile.ToString()))
            {
                Directory.CreateDirectory(strFile.ToString());
                create = true;
            }
            //将数据写入文件中
            strFile.Append(DateTime.Now.ToString("yyyy-MM-dd") + ".txt");
            using (StreamWriter swAppend = File.AppendText(strFile.ToString()))
            {
                StringBuilder str = new StringBuilder();
                str.AppendFormat("[{0}][{1}][{2}]{3}", mSum, DateTime.Now, DateTime.Now.Millisecond.ToString("d4"), strData);
                swAppend.WriteLine(Convert.ToString(str));
                swAppend.Flush();
                swAppend.Close();
            }
            mSum++;

        }
         private  struct printlogST
        {
            public StringBuilder strb;
 
        }
         private List<printlogST> printstring = new List<printlogST>();
        private static readonly object obj_Log = new object();//日志文件读写同步锁
        private void WriteLog(string strData,TextBox textbox1)
        {
            try
            {
                Monitor.Enter(obj_Log);
                printlogST prt = new printlogST();
    
                mSum++;
                StringBuilder str = new StringBuilder();
                str.AppendFormat("[{0}][{1}][{2}]{3}", mSum, DateTime.Now, DateTime.Now.Millisecond.ToString("d4"), strData);
                prt.strb = str;
                lock (_plock)
                {
                    printstring.Add(prt);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return;
            }
            finally
            {
                Monitor.Exit(obj_Log);
            }
        }
        public void WriteCommonLog(string strData)
        {
            try
            {
                Monitor.Enter(obj_Log);
                printlogST prt = new printlogST();

                StringBuilder str = new StringBuilder();
                str.AppendFormat("[{0}][{1}-{2}][{3}]{4}", mSum, DateTime.Now, DateTime.Now.Millisecond.ToString("d4"), _LogStrClassify.Common.ToString(), strData);
                mSum++;
                prt.strb = str;
                lock (_plock)
                {
                    printstring.Add(prt);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return;
            }
            finally
            {
                Monitor.Exit(obj_Log);
            }
        }
        public void WriteLog( _LogStrClassify cy, string strData)
        {
            try
            {
                Monitor.Enter(obj_Log);
                printlogST prt = new printlogST();
                     
                StringBuilder str = new StringBuilder();
                str.AppendFormat("[{0}][{1}-{2}][{3}]{4}", mSum, DateTime.Now, DateTime.Now.Millisecond.ToString("d4"), cy.ToString(),strData);  
                mSum++;
                prt.strb = str;
                lock (_plock)
                {
                    printstring.Add(prt);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return;
            }
            finally
            {
                Monitor.Exit(obj_Log);
            }
        }

    }
}
